package com.etogc.groupchat.main;

import android.annotation.SuppressLint;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.etogc.groupchat.R;
import com.etogc.groupchat.find.FindFragment;
import com.etogc.groupchat.group.frgm.AllGroupFragment;
import com.etogc.groupchat.group.frgm.GroupFragment;
import com.etogc.groupchat.group.ui.CreateGroupActivity;
import com.etogc.groupchat.group.ui.JoinGroupActivity;
import com.etogc.groupchat.mine.MineFragment;
import com.etogc.http.ReqDataHandler;
import com.etogc.http.ReqErrorHandler;
import com.etogc.http.VolleyHttpUtil;
import com.etogc.util.GcUrl;
import com.etogc.util.ImageUtils;
import com.etogc.util.IntentHelper;
import com.etogc.util.YcToastHelper;
import com.etogc.view.righttopmenu.MenuItem;
import com.etogc.view.righttopmenu.RightTopMenu;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import io.rong.imkit.RongIM;
import io.rong.imkit.manager.IUnReadMessageObserver;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Group;
import io.rong.imlib.model.UserInfo;

public class MainActivity extends FragmentActivity implements ViewPager.OnPageChangeListener, View.OnClickListener {

    public static ViewPager mViewPager;
    private List<Fragment> mFragment = new ArrayList<>();
    private ImageView ivMain;
    private ImageView ivGroup;
    private ImageView ivMine;
    private ImageView ivFind;
    private TextView tvTitle;
    //    ic_private ImageView ivBack;
    private ImageView ivRight;
    private TextView tvUnread;
    private RightTopMenu mRightTopMenu;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initViewPager();
        initRong();
//        getUserInfo();
        getGruopInfo();
    }

    /**
     * 刷新群组信息
     */
    private void getGruopInfo() {
        RongIM.setGroupInfoProvider(new RongIM.GroupInfoProvider() {
            @Override
            public Group getGroupInfo(String s) {
                final Group[] groupInfo = new Group[1];
                MainBiz.getGroupInfo(s, new VolleyHttpUtil.ResponseCallBack() {
                    @Override
                    public void handleResponse(JSONObject response, int errCode) {
                        boolean isOk = ReqErrorHandler.getInstance().isSuccess(response, true);
                        Log.e("Biz", response.toString());
                        if (isOk) {
                            Map<String, Object> map = ReqDataHandler.getMapWithEntityNoGson(response);
                            if (map != null) {
                                Map<String, Object> mapUser = (Map<String, Object>) map.get("groupinfo");
                                String nickName = String.valueOf(mapUser.get("group_name"));
                                String userID = String.valueOf(mapUser.get("id"));
                                String photo = ImageUtils.getImageUrl(String.valueOf(mapUser.get("photo")));
                                groupInfo[0] = new Group(userID, nickName, Uri.parse(photo));
                                RongIM.getInstance().refreshGroupInfoCache(groupInfo[0]);
                            }
                        }
                    }
                });
                return groupInfo[0];
            }
        }, true);
    }


    private void initRong() {
//        RongIM.init(this);
//        RongIM.setOnReceiveMessageListener(new RongIMClient.OnReceiveMessageListener() {
//            @Override
//            public boolean onReceived(Message message, int i) {
//                Log.e("testMsg", "msg=" + String.valueOf(message.getContent().toString()));
//                return false;
//            }
//        });
        //获取未读信息
        Conversation.ConversationType[] conversationTypes = {
                Conversation.ConversationType.GROUP,
                Conversation.ConversationType.SYSTEM,
                Conversation.ConversationType.PUBLIC_SERVICE,
                Conversation.ConversationType.APP_PUBLIC_SERVICE
        };
        RongIM.getInstance().addUnReadMessageCountChangedObserver(new IUnReadMessageObserver() {
            @Override
            public void onCountChanged(int i) {
                if (i > 0) {
                    tvUnread.setVisibility(View.VISIBLE);
                    tvUnread.setText(String.valueOf(i));
                } else {
                    tvUnread.setVisibility(View.GONE);
                }
            }
        }, conversationTypes);
    }

    private void initView() {
        ivFind = findViewById(R.id.ivFind);
        ivGroup = findViewById(R.id.ivGroup);
        ivMain = findViewById(R.id.ivMain);
        ivMine = findViewById(R.id.ivMine);
        tvTitle = findViewById(R.id.tvTitle);
        tvUnread = findViewById(R.id.tv_unread);
        ivRight = findViewById(R.id.ivRight);
        mViewPager = findViewById(R.id.main_viewpager);
        findViewById(R.id.layoutMine).setOnClickListener(this);
        findViewById(R.id.layoutMain).setOnClickListener(this);
        findViewById(R.id.layoutGroup).setOnClickListener(this);
        findViewById(R.id.layoutFind).setOnClickListener(this);
        ivRight.setVisibility(View.INVISIBLE);
        ivRight.setOnClickListener(this);
    }

    private void initViewPager() {
        mFragment.add(new AllGroupFragment());
        mFragment.add(new GroupFragment());
        mFragment.add(new FindFragment());
        mFragment.add(new MineFragment());
        FragmentPagerAdapter fragmentPagerAdapter = new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                return mFragment.get(position);
            }

            @Override
            public int getCount() {
                return mFragment.size();
            }
        };
        mViewPager.setAdapter(fragmentPagerAdapter);
        mViewPager.setOffscreenPageLimit(4);
        mViewPager.setOnPageChangeListener(this);
    }

    private void changeTextViewColor() {

    }

    private void changeSelectedTabState(int position) {
        switch (position) {
            case 0:
                mViewPager.setCurrentItem(0, false);
                ivMine.setBackgroundResource(R.drawable.tab_me);
                ivFind.setBackgroundResource(R.drawable.tab_finds);
                ivGroup.setBackgroundResource(R.drawable.tab_chat);
                ivMain.setBackgroundResource(R.drawable.tab_home_hover);
                ivRight.setVisibility(View.GONE);
                tvTitle.setText("首页");
                break;
            case 1:
                mViewPager.setCurrentItem(1, false);
                ivMine.setBackgroundResource(R.drawable.tab_me);
                ivFind.setBackgroundResource(R.drawable.tab_finds);
                ivGroup.setBackgroundResource(R.drawable.tab_chat_hover);
                ivMain.setBackgroundResource(R.drawable.tab_home);
                ivRight.setVisibility(View.VISIBLE);
                tvTitle.setText("群聊");
                break;
            case 2:
                mViewPager.setCurrentItem(2, false);
                ivFind.setBackgroundResource(R.drawable.tab_finds_hover);
                ivMine.setBackgroundResource(R.drawable.tab_me);
                ivGroup.setBackgroundResource(R.drawable.tab_chat);
                ivMain.setBackgroundResource(R.drawable.tab_home);
                tvTitle.setText("发现");
                ivRight.setVisibility(View.GONE);
                break;
            case 3:
                mViewPager.setCurrentItem(3, false);
                ivMine.setBackgroundResource(R.drawable.tab_me_hover);
                ivGroup.setBackgroundResource(R.drawable.tab_chat);
                ivFind.setBackgroundResource(R.drawable.tab_finds);
                ivMain.setBackgroundResource(R.drawable.tab_home);
                tvTitle.setText("我的");
                ivRight.setVisibility(View.GONE);
                break;
        }
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        changeTextViewColor();
        changeSelectedTabState(position);
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.layoutMain:
                changeSelectedTabState(0);
                break;
            case R.id.layoutGroup:
                changeSelectedTabState(1);
                break;
            case R.id.layoutFind:
                changeSelectedTabState(2);
                break;
            case R.id.layoutMine:
                changeSelectedTabState(3);
                break;
            case R.id.ivRight:
                jumpAddGroup(view);
                break;
        }
    }

    private void jumpAddGroup(View view) {
        showRightTopMenu(view);
        //
    }

    private void showRightTopMenu(View view) {
        List<MenuItem> menuItems = new ArrayList<>();
        menuItems.add(new MenuItem("申请群"));
        menuItems.add(new MenuItem("加入群"));
        if (mRightTopMenu == null) {
            mRightTopMenu = new RightTopMenu.Builder(MainActivity.this)
                    .windowHeight(120)     //当菜单数量大于3个时，为wrap_content,反之取默认高度320
//                    .windowWidth(160)      //默认宽度wrap_content
                    .dimBackground(true)           //背景变暗，默认为true
                    .needAnimationStyle(true)   //显示动画，默认为true
                    .animationStyle(R.style.RTM_ANIM_STYLE)  //默认为R.style.RTM_ANIM_STYLE
                    .menuItems(menuItems)
                    .onMenuItemClickListener(new RightTopMenu.OnMenuItemClickListener() {
                        @Override
                        public void onMenuItemClick(int position) {
                            switch (position) {
                                case 0:
                                    jumpToAdd();
                                    break;
                                case 1:
                                    jumpToJoin();
                                    break;
                            }
//                            Toast.makeText(MainActivity.this, "点击菜单:" + position, Toast.LENGTH_SHORT).show();
                        }
                    }).build();
        }
        mRightTopMenu.showAsDropDown(view, -30, 0);
    }

    private void jumpToJoin() {
        IntentHelper.getInstances().getIntent(this, JoinGroupActivity.class);
    }

    private void jumpToAdd() {
        IntentHelper.getInstances().getIntent(this, CreateGroupActivity.class);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            moveTaskToBack(false);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onBackPressed() {
        exit();
    }

    private boolean isExit;
    @SuppressLint("HandlerLeak")
    Handler mHandler2 = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
            isExit = false;
        }
    };

    /**
     * 双击退出的方法体
     */
    public void exit() {
        if (!isExit) {
            isExit = true;
            YcToastHelper.getInstance()._toast("再次点击退出APP");
            mHandler2.sendEmptyMessageDelayed(0, 2000);
        } else {
            this.finish();
        }
    }
}
